#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
支付配置管理API
"""

from flask import request, current_app
from flasgger import swag_from
from datetime import datetime
from app import db
from app.models.payment_config import PaymentConfig
from app.utils.response import success_response, error_response
from app.utils.decorators import admin_required
from app.api.v1 import api_v1


@api_v1.route('/admin/payment-configs', methods=['GET'])
@admin_required
@swag_from({
    "tags": ["支付配置管理"],
    "summary": "获取支付配置列表",
    "description": "管理员获取支付配置列表\n\n**🔐 需要管理员Token认证**",
    "security": [{"Bearer": []}],
    "responses": {
        "200": {"description": "获取成功"},
        "401": {"description": "未授权访问"},
        "500": {"description": "服务器内部错误"}
    }
})
def get_payment_configs():
    """获取支付配置列表"""
    try:
        configs = PaymentConfig.query.order_by(PaymentConfig.created_at.desc()).all()
        return success_response([config.to_dict() for config in configs], '获取支付配置成功')
    except Exception as e:
        current_app.logger.error(f"获取支付配置失败: {str(e)}")
        return error_response('获取支付配置失败', 500)


@api_v1.route('/admin/payment-configs', methods=['POST'])
@admin_required
@swag_from({
    "tags": ["支付配置管理"],
    "summary": "创建支付配置",
    "description": "管理员创建新的支付配置\n\n**🔐 需要管理员Token认证**",
    "security": [{"Bearer": []}],
    "responses": {
        "200": {"description": "创建成功"},
        "400": {"description": "请求参数错误"},
        "401": {"description": "未授权访问"},
        "500": {"description": "服务器内部错误"}
    }
})
def create_payment_config():
    """创建支付配置"""
    try:
        data = request.get_json()
        if not data:
            return error_response('请求数据不能为空', 400)
        
        # 验证必填字段
        if not data.get('name'):
            return error_response('配置名称不能为空', 400)
        
        if not data.get('payment_method'):
            return error_response('支付方式不能为空', 400)
        
        # 如果设置为启用，先禁用同类型的其他配置
        if data.get('is_enabled', True):
            PaymentConfig.query.filter_by(
                payment_method=data['payment_method'],
                is_enabled=True
            ).update({'is_enabled': False})
        
        # 创建配置
        config = PaymentConfig(
            name=data['name'],
            payment_method=data['payment_method'],
            is_enabled=data.get('is_enabled', True),
            wechat_app_id=data.get('wechat_app_id'),
            wechat_mch_id=data.get('wechat_mch_id'),
            wechat_api_key=data.get('wechat_api_key'),
            wechat_notify_url=data.get('wechat_notify_url'),
            timeout_seconds=data.get('timeout_seconds', 1800),
            is_sandbox=data.get('is_sandbox', False)
        )
        
        db.session.add(config)
        db.session.commit()
        
        return success_response(config.to_dict(), '支付配置创建成功', 200)
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"创建支付配置失败: {str(e)}")
        return error_response('创建支付配置失败', 500) 